
import 'package:huxiaodui/utils/global_controller.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

import 'model_base.dart';

class MobileAppModel extends ModelBase {
  static List<String> jobList = [
    "",
    "学生",
    "学生家长",
    "保安",
    "教师",
    "医生",
    "社会自愿者",
    "保卫科长",
    "校长",
    "院长",
    "民警"
  ];

  final String account;
  final String name;
  final String sex;
  final String tel;
  final bool root;
  final DateTime onlineAt;
  final int job;
  final String addr;
  late final String email;
  final double? latitude;
  final double? longitude;
  final DateTime locationAt;
  final LatLng? latLng;

  // 构造函数，通过 Map 初始化
  MobileAppModel({
    required super.id,
    required super.createdAt,
    required this.account,
    this.name = "",
    this.sex = "",
    this.tel = "",
    this.job = 0,
    this.addr = "",
    this.root = false,
    this.email = "",
    this.latitude,
    this.longitude,
    required this.locationAt,
  })  : onlineAt = DateTime.now(), // 默认当前时间
        latLng = (latitude != null && longitude != null && latitude != 0 && longitude != 0)
            ? LatLng(latitude, longitude)
            : null;

  // 工厂构造函数，通过 JSON Map 创建 MobileApp 实例
  factory MobileAppModel.fromJson(Map<String, dynamic> map) {
    DateTime onlineAt = DateTime.fromMillisecondsSinceEpoch(map["onlineAt"] ?? 0);
    DateTime locationAt = DateTime.fromMillisecondsSinceEpoch(map["locationAt"] ?? 0);

    return MobileAppModel(
      id: map["id"] ?? -1,
      createdAt: DateTime.fromMillisecondsSinceEpoch(map["createdAt"] ?? 0),
      account: map["account"] ?? "",
      name: map["name"] ?? "",
      sex: map["sex"] ?? "",
      tel: map["tel"] ?? "",
      job: map["job"] ?? 0,
      addr: map["addr"] ?? "",
      root: map["root"] ?? false,
      email: map["email"] ?? "",
      latitude: map["latitude"] != null && map["latitude"] != 0
          ? double.parse(map["latitude"].toString())
          : null,
      longitude: map["longitude"] != null && map["longitude"] != 0
          ? double.parse(map["longitude"].toString())
          : null,
      locationAt: locationAt,
    );
  }

  // 将 MobileApp 实例转换为 JSON Map
  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "createdAt": createdAt.millisecondsSinceEpoch,
      "account": account,
      "name": name,
      "sex": sex,
      "tel": tel,
      "job": job,
      "addr": addr,
      "root": root,
      "email": email,
      "latitude": latitude,
      "longitude": longitude,
      "locationAt": locationAt.millisecondsSinceEpoch,
    };
  }

  // 静态方法，将动态数据转换为 MobileApp 列表
  static List<MobileAppModel> toList(dynamic res) {
    var data = List<Map<String, dynamic>>.from(res);
    return data.map((map) => MobileAppModel.fromJson(map)).toList();
  }
}
